import json
from PIL import Image
import random
import random_name
import filenamee
import os

# 随机截图的
# 时间复杂度n^4

# 循环次数
num = 1
# 文件地址
# pic_folder = 'D:/pic'
pic_folder = 'C:/Users/EDY/Desktop/qian1'
# 保存位置
folder_path = 'D:/new/'
# 调用函数,如果json和图片文件有且相同则存入数组same_name_files
same_name_files = random_name.get_same_name_files(pic_folder)

for i in same_name_files:
    # 读取图片
    img = Image.open(pic_folder + "/" + i[0])
    # 读取JSON文件
    with open(pic_folder + '/' + i[1], 'r', encoding='utf-8') as f:
        data = json.load(f)
    # 提取坐标
    li = list()
    for shape in list(data['shapes']):
        print(shape['label'])
        li.append(shape['label'])
    for v in li:
        coordinates = []
        for shape in data['shapes']:
            if shape['label'] == v:
                for point in shape['points']:
                    coordinates.append((point[0], point[1]))
        lens=int(len(coordinates) / 2)
        print("lens"+str(lens))
        for j in range(lens):
            le = round(coordinates[j * 2][0])
            u = round(coordinates[j * 2][1])
            r = round(coordinates[j * 2 + 1][0])
            lo = round(coordinates[j * 2 + 1][1])
            # 控制x方向的坐标
            for k in range(num):
                print("num"+str(num))
                xx = random.randint(-1, 1)
                yy = random.randint(-1, 1)
                # 生成随机左上角和右下角坐标
                left = le + xx
                upper = u + yy
                right = r + xx
                lower = lo + yy

                if left > right:
                    left, right = right, left
                if upper > lower:
                    upper, lower = lower, upper
                # 剪裁图像
                cropped = img.crop((left, upper, right, lower))
                # 查看图片
                # Image._show(cropped)
                # 随机生产6位随机数加大小写字母
                f_name = filenamee.generate_random_filename(6)
                # 生成随机文件名
                filename = "pil_cut_" + f_name + ".png"
                # filename = i[1] + f_name + ".png"
                # 如果没有文件夹就创建
                if not os.path.exists(folder_path + '/' + v):
                    os.makedirs(folder_path + '/' + v)
                # 保存剪裁后的图像
                cropped.save("D:/new/" + v + '/' + filename)
